﻿using System;
using System.Globalization;
using System.Linq;
using System.Web.Profile;
using System.Web.Security;
using System.Web.UI.WebControls;
using Medianamik.Core;
using Medianamik.Core.Profile;
using Medianamik.Core.Security;
using Medianamik.Globalization;
using Roles = Medianamik.Core.Security.Roles;

namespace Medianamik.UI.SecurityManagement
{
    public partial class AddUser : BasePage
    {
        #region Événements

        protected void Page_Init(object sender, EventArgs e)
        {
            lnkSave.Click += lnkSave_Click;
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                BindData();
                calExpirationDate.DatePopupButton.ToolTip = Resources("Medianamik_Controls", "OpenCalendarPopup");
            }
        }

        protected void cvUsername_ServerValidate(object sender, ServerValidateEventArgs e)
        {
            e.IsValid = Membership.GetUser(e.Value, false) == null;
        }

        protected void cvPasswordStrength_ServerValidate(object sender, ServerValidateEventArgs e)
        {
            var password = e.Value;
            var validator = new PasswordValidator(Membership.Provider);
           var result =  validator.ValidatePassword(password);

           e.IsValid = result == PasswordValidationResult.Success;            
        }

        protected void cvPasswordCompare_ServerValidate(object sender, ServerValidateEventArgs e)
        {
            var password = e.Value;
            var comparePassword = txtConfirmPassword.Text;

            e.IsValid = password.CompareTo(comparePassword) == 0; 
        }

       

        /// <summary>
        /// Sauvegarder le nouvel usager
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void lnkSave_Click(object sender, EventArgs e)
        {
            if (Page.IsValid)
            {
                SaveData();

                Response.Redirect("UserList.aspx");
            }
        }

        protected void chkAutoGeneratePwd_CheckedChanged(object sender, EventArgs e)
        {
            if (chkAutoGeneratePwd.Checked)
            {
                mvPassword.SetActiveView(vwNoPassword);
            }
            else
            {
                mvPassword.SetActiveView(vwPassword);
            }
        }

        #endregion

        #region Méthodes

        /// <summary>
        /// Obtenir les donnés de base du formulaire
        /// </summary>
        private void BindData()
        {

            cblGroups.DataBind();

            ddlLanguage.DataSource = ConfigManager.GetMedianamikCultures().Select(c=>c.CultureInfo );
            ddlLanguage.DataBind();

            calExpirationDate.SelectedDate = null;
            calExpirationDate.MinDate = DateTime.Today;
            calExpirationDate.MaxDate = DateTime.Today.AddYears(10);
            calExpirationDate.DateInput.SelectedDate = default(DateTime?);
            calExpirationDate.FocusedDate = DateTime.Today;
            calExpirationDate.Culture = CurrentUICulture;

            if (chkAutoGeneratePwd.Checked)
            {
                mvPassword.SetActiveView(vwNoPassword);
            }
            else
            {
                mvPassword.SetActiveView(vwPassword);
            }

        }

        /// <summary>
        /// Créer l'usager 
        /// </summary>
        private void SaveData()
        {
            // Génération de mot de passe
            string password = chkAutoGeneratePwd.Checked ? Membership.GeneratePassword(10, 3) : txtPassword.Text;
            
            // Création d'utilisateur
            var user = Membership.CreateUser(txtUserName.Text, password, txtEmail.Text);
            user.IsApproved = chkApproved.Checked;
            Membership.UpdateUser(user);
            
            // Création d'un profil
            var profile = (UserProfile)ProfileBase.Create(user.UserName);
            if (!string.IsNullOrEmpty(ddlLanguage.SelectedValue))
            {
                profile.UICultureName = ddlLanguage.SelectedValue;
            }
            profile.FullName = txtCompleteName.Text;
            profile.ExpirationDate = calExpirationDate.SelectedDate;
            profile.Save();

            Core.Logging.LogEntryManager.LogUser(user, "User Created");

            // Roles
			var selectedRoles = cblGroups.Items.Cast<ListItem>().Where(i => i.Selected).Select(i => i.Value).ToArray();
			Roles.AddUserToGroups(user.UserName, selectedRoles);

            // Envoi de courriel
            if (chkEmail.Checked)
            {
                new Core.Mail.MailManager().SendNewUserConfirmationMessage(user, CultureInfo.GetCultureInfo(profile.UICultureName), password, Context ); 
            }

        }

        #endregion
    }
}
